package dryven.util.json.dryvenjson;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

import dryven.model.binding.proxy.Binding;
import dryven.model.di.LocalThreadStorage;
import dryven.util.BeanUtil;

public class BoundFieldPolicy implements FieldPolicy {

	private List<Method> _allowMethods = new LinkedList<Method>();
	private BeanUtil beanUtil = new BeanUtil();

	public BoundFieldPolicy addField(Binding binding) {
		return addMethod(binding.getBoundMethod());
	}
	
	public BoundFieldPolicy addMethod(Method m) {
		_allowMethods.add(m);
		return this;
	}
	
	@Override
	public boolean includeField(Field f) {
		return false;
	}

	@Override
	public String getFieldName(Field f) {
		return null;
	}

	@Override
	public boolean includeMethod(Method m) {
		for (Method method: _allowMethods) {
			if(method.equals(m)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public Object getValueFromMethod(Method m, Object object,
			LocalThreadStorage diStorage) {
		try {
			return m.invoke(object, null);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public Object getValueFromField(Field f, Object object,
			LocalThreadStorage diStorage) {
		return null;
	}

	@Override
	public String getFieldName(Method m) {
		return beanUtil.getPropertyName(m);
	}

}
